import Cookie from 'js-cookie'
export default {
  state: {
    isCollapse: false,
    menu: [],
    currentMenu: null,
    tabsList: [{ path: '/', name: 'home', label: '首页', icon: 'home', type: 'danger' }],
  },
  mutations: {
    selectMenu(state, value) {
      if (value.name != 'home') {
        state.currentMenu = value
        let result = state.tabsList.findIndex((item) => item.name === value.name)
        result === -1 ? state.tabsList.push(value) : ''
      } else {
        state.currentMenu = null
      }
    },
    // 登陆以后
    setMenu(state, value) {
      state.menu = value
      // cookie 名字是menu  然后把valu值转为 json字符串
      Cookie.set('menu', JSON.stringify(value))
    },
    // 退出登录 把cookie清除
    clearMenu(state) {
      state.menu = []
      Cookie.remove('menu')
    },
    addMenu(state, router) {
      if (!Cookie.get('menu')) {
        return
      }
      let menu = JSON.parse(Cookie.get('menu'))
      state.menu = menu
      // 添加动态路由的数组
      let currentMenu = [
        {
          path: '/',
          component: () => import('@/views/main.vue'),
          children: [],
        },
      ]
      menu.forEach((item) => {
        if (item.children) {
          item.children = item.children.map((item) => {
            // item就是 二级菜单
            item.component = () => import(`@/views/${item.url}`)
            return item
          })
          // 由于item.children 是一个数组 需要把它拉平
          currentMenu[0].children.push(...item.children)
        } else {
          item.component = () => import(`@/views/${item.url}`)
          currentMenu[0].children.push(item)
        }
      })
      router.addRoutes(currentMenu)
    },
    // 关闭tag标签
    closeTab(state, value) {
      let result = state.tabsList.findIndex((item) => item.name === value.name)
      state.tabsList.splice(result, 1)
    },
    collapseMenu(state) {
      state.isCollapse = !state.isCollapse
    },
  },
  actions: {},
  modules: {},
}
